package com.yunxi.rocketmq.config;

import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * Created by Administrator on 2019/6/16.
 */
@Component
public class RocketMQConfig {




    public static Producer producer;
    public static Properties properties;

    @Value("${aliyun.rocketMQ.accessKey}")
    private String accessKey;
    @Value("${aliyun.rocketMQ.secretKey}")
    private String secretKey;
    @Value("${aliyun.rocketMQ.sendMsgTimeoutMillis}")
    private String sendMsgTimeoutMillis;
    @Value("${aliyun.rocketMQ.namesrvAddr}")
    private String namesrvAddr;
    @Value("${aliyun.rocketMQ.eai.log.producerGroup}")
    private String group;


    /**
     * 初始化参数
     *
     * @return
     */
    public  Properties getProperties() {

        if (properties == null) {
            properties = new Properties();
        }
        // AccessKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.AccessKey,accessKey );
        // SecretKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.SecretKey, secretKey);
        //设置发送超时时间，单位毫秒
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, sendMsgTimeoutMillis);
        // 设置 TCP 接入域名，进入控制台的实例管理页面的“获取接入点信息”区域查看
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
                namesrvAddr);
        properties.put(PropertyKeyConst.GROUP_ID,group);
        return properties;
    }

    /**
     * 初始化生产者
     *
     * @return
     */
    public Producer getProducer() {
        properties = new Properties();
        properties.put(PropertyKeyConst.AccessKey,accessKey );
        // SecretKey 阿里云身份验证，在阿里云服务器管理控制台创建
        properties.put(PropertyKeyConst.SecretKey, secretKey);
        //设置发送超时时间，单位毫秒
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, sendMsgTimeoutMillis);
        // 设置 TCP 接入域名，进入控制台的实例管理页面的“获取接入点信息”区域查看
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
                namesrvAddr);
        properties.put(PropertyKeyConst.GROUP_ID,group);
        if (producer == null || producer.isClosed()) {
            producer = ONSFactory.createProducer(properties);
            System.out.println("===RocketMQ生产者启动===");
            producer.start();
        }
        return producer;
    }

}
